import time
sta = time.time()

a = 0 ###
ma = 8297
votefile = "Wiki-Vote.txt"
ratefile = "linkrate0.txt"
threshStop = 0.00000001

global link
global data
global lastrate
global nowrate
#获取所有链接字典
def GetLinkDict():
    global link
    seq = [x for x in range(1, ma+1)]
    link = dict.fromkeys(seq)
    # count = 1
    fopen = open(votefile)
    for line in fopen:
        if line[0] == '#':
            continue
        edge = line.split()
        x, y = [int(x) for x in edge]
        if link[x] is None:
            link[x] = []
        link[x].append(y)
        # for lin in link.items():
        #     print(lin)
# 初始化节点 概率
def InitLinkRate():
    fopen = open(ratefile,'w')
    i = 1
    while i <= ma:
        fopen.write(str(1/ma)+' ')
        i += 1
def GetPR():
    global lastrate
    global nowrate
    sum = [0 for i in range(1, ma + 1)]
    fopen = open(ratefile,'r')
    data = fopen.read()
    data = data.split()
    lastrate = float(data[2])
    for item in range(1,ma+1):
        outlink = link[item]
        if outlink is None:
            sum[item-1] += float(data[item-1])
            continue
        trate = float(data[item-1])/len(outlink)
        for j in outlink:
            sum[j-1] += trate
    fopen = open(ratefile,'w')
    for item in range(0,ma):
        rate = a * sum[item] + (1-a)/ma
        fopen.write(str(rate) + ' ')
        if item == 2:
            nowrate = rate
            print(rate)


#获取所有链接字典
GetLinkDict()
#初始化
InitLinkRate()
count = 0
while True:
    GetPR()
    #设置停止迭代条件
    count += 1
    # if count >= 10:
    #     break
    if abs(lastrate - nowrate) <= threshStop:
        break

#对结果进行排序，输出top 50
end = time.time()

print("总共时间消耗：",end-sta)
print("迭代次数：",count)